package kr.co.sdworld.common.util;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringApplicationContextListener implements ServletContextListener
{
	private Logger logger = Logger.getLogger(SpringApplicationContextListener.class);
	
	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		SpringWebContext.setWebApplicationContext(wac);
		
		logger.debug("Loading config.properties...");
		ClassPathResource classPathResource = new ClassPathResource( "config.properties");
		try {
			GlobalConfig.load(classPathResource.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		logger.debug("complete...!");
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		SpringWebContext.setWebApplicationContext(null);
	}
}
